﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ToDoBasket.Core;
using ToDoBasket.Custom;
using ToDoBasket.Model;

namespace ToDoBasket
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<Potato> List { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            InitializeData();
            InitializeEvent();
        }
        //初始化数据
        public void InitializeData()
        {
            List = XmlManager.Instance.Load();
            lbPotato.ItemsSource = List;
        }

        //初始化事件
        public void InitializeEvent()
        {
            MouseLeftButtonDown += (s, e) => { DragMove(); };
            tbIcon.PreviewMouseLeftButtonDown += (s, e) => new AboutWindow { Owner = this }.ShowDialog();
            tbPotato.EnterPressed += tbPotato_EnterPressed;
            btnClose.Click += (s, e) =>
            {
                XmlManager.Instance.Save(List);
                Storyboard sb = new Storyboard();
                DoubleAnimation da = new DoubleAnimation
                {
                    To = 0,
                    Duration = TimeSpan.FromSeconds(0.3)
                };
                Storyboard.SetTarget(da, this);
                Storyboard.SetTargetProperty(da, new PropertyPath(OpacityProperty));
                sb.Children.Add(da);
                sb.Completed += (ss, ee) => Close();
                sb.Begin();
            };
            menuBtnClear.Click += (s, e) =>
            {
                for (int i = 0; i < List.Count; i++)
                {
                    if (List[i].IsFinished == true) List.RemoveAt(i--);
                }
            };
            gdTitle.MouseRightButtonDown += (s, e) => WindowState = WindowState.Minimized;
        }

        #region 调整窗体大小、禁止最大化

        [DllImport("user32.dll")]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("user32.dll")]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll")]
        private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            //禁止最大化
            int GWL_STYLE = -16;
            int WS_MAXIMIZEBOX = 0x00010000;
            int SWP_NOSIZE = 0x0001;
            int SWP_NOMOVE = 0x0002;
            int SWP_FRAMECHANGED = 0x0020;
            var hwnd = new WindowInteropHelper(this).Handle;
            var value = GetWindowLong(hwnd, GWL_STYLE);
            SetWindowLong(hwnd, GWL_STYLE, (int)(value & ~WS_MAXIMIZEBOX));
            SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
            //拖拽调整窗体大小
            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
            if (hwndSource != null) hwndSource.AddHook(new HwndSourceHook(WndProc));
        }

        private const int WM_NCHITTEST = 0x0084;
        private readonly int radius = 16;
        private readonly int borderThickness = 12;
        private Point mousePoint = new Point();

        protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_NCHITTEST)
            {
                mousePoint.X = (lParam.ToInt32() & 0xFFFF);
                mousePoint.Y = lParam.ToInt32() >> 16;
                handled = true;
                // 窗口右下角  
                if (ActualWidth + Left - mousePoint.X <= radius && ActualHeight + Top - mousePoint.Y <= radius)
                    return new IntPtr((int)HitTest.HTBOTTOMRIGHT);
                // 窗口左上角  
                if (mousePoint.Y - Top <= radius && mousePoint.X - Left <= radius)
                    return new IntPtr((int)HitTest.HTTOPLEFT);
                // 窗口左下角　　  
                if (ActualHeight + Top - mousePoint.Y <= radius && mousePoint.X - Left <= radius)
                    return new IntPtr((int)HitTest.HTBOTTOMLEFT);
                // 窗口右上角  
                if (mousePoint.Y - Top <= radius && ActualWidth + Left - mousePoint.X <= radius)
                    return new IntPtr((int)HitTest.HTTOPRIGHT);
                // 窗口右侧  
                if (ActualWidth + Left - mousePoint.X <= borderThickness)
                    return new IntPtr((int)HitTest.HTRIGHT);
                // 窗口下方  
                if (ActualHeight + Top - mousePoint.Y <= borderThickness)
                    return new IntPtr((int)HitTest.HTBOTTOM);
                // 窗口左侧  
                if (mousePoint.X - Left <= borderThickness)
                    return new IntPtr((int)HitTest.HTLEFT);
                // 窗口上方  
                if (mousePoint.Y - Top <= borderThickness)
                    return new IntPtr((int)HitTest.HTTOP);
                handled = false;
            }
            return IntPtr.Zero;
        }

        #endregion

        //新建土豆
        void tbPotato_EnterPressed(object sender, EnterPressedRoutedEventArgs e)
        {
            Potato potato = e.NewPotato;
            //Debug.WriteLine("original:" + potato.Original + " prefix:" + potato.Prefix + " description:" + potato.Description);
            if (e.Lowest)
                List.Insert(List.Count, potato);
            else
                List.Insert(0, potato);
            lbPotato.ScrollIntoView(potato);
        }

        //删除土豆项
        private void PotatoItem_OnBtnDeleteClick(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("del");
            PotatoItem item = sender as PotatoItem;
            if (item == null) return;
            Potato potato = item.DataContext as Potato;
            if (potato == null) return;
            //删除动画
            Storyboard sb = new Storyboard();
            DoubleAnimation an = new DoubleAnimation { To = 0, Duration = TimeSpan.FromSeconds(0.2) };
            DoubleAnimation an2 = new DoubleAnimation { From = item.ActualHeight, To = 0, BeginTime = TimeSpan.FromSeconds(0.1), Duration = TimeSpan.FromSeconds(0.2) };
            Storyboard.SetTarget(an, item);
            Storyboard.SetTargetProperty(an, new PropertyPath(PotatoItem.OpacityProperty));
            Storyboard.SetTarget(an2, item);
            Storyboard.SetTargetProperty(an2, new PropertyPath(PotatoItem.HeightProperty));
            sb.Children.Add(an);
            sb.Children.Add(an2);
            //动画结束时删除对象
            sb.Completed += (s, ee) => List.Remove(potato);
            sb.Begin();
        }

        //前缀（标签）筛选
        private void PotatoItem_OnBtnPrefixClick(object sender, RoutedEventArgs e)
        {
            PotatoItem item = sender as PotatoItem;
            if (item == null) return;
            Potato potato = item.DataContext as Potato;
            if (potato == null || potato.Prefix.Equals("")) return;
            tbPotato.Prefix = potato.Prefix;
            foreach (Potato p in List)
            {
                if (!p.Prefix.Equals(potato.Prefix))
                {
                    ListBoxItem listBoxItem = lbPotato.ItemContainerGenerator.ContainerFromItem(p) as ListBoxItem;
                    if (listBoxItem == null) continue;
                    listBoxItem.Visibility = Visibility.Collapsed;
                }
            }
        }

        //取消前缀（标签）筛选
        private void TbPotato_OnBtnClearClick(object sender, RoutedEventArgs e)
        {
            foreach (Potato p in List)
            {
                ListBoxItem listBoxItem = lbPotato.ItemContainerGenerator.ContainerFromItem(p) as ListBoxItem;
                if (listBoxItem == null) continue;
                listBoxItem.Visibility = Visibility.Visible;
            }
        }

        /*#region 移动土豆

        private StackPanel pn;
        private Potato movingPotato;
        //private Border tempItem;
        //是否正在移动
        private bool CanMove()
        {
            return movingPotato != null;
        }

        private void MoveStart(Potato potato)
        {
            movingPotato = potato;
        }

        private void Moving(Point p)
        {
            if (!CanMove()) return;
            int index = (int)(Math.Floor(p.Y / 34));
            Debug.WriteLine(p.Y + "::" + index);
            if (index == List.IndexOf(movingPotato)) return;
            Debug.WriteLine("move");
            if (index > List.Count - 1) index = List.Count - 1;
            else if (index < 0) index = 0;
            List.Remove(movingPotato);
            List.Insert(index, movingPotato);
        }
        private void PnPotato_OnLoaded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("load");
            pn = sender as StackPanel;
        }
        private void MoveFinish()
        {
            if (!CanMove()) return;
            movingPotato = null;
        }

        private void LbPotato_OnMouseMove(object sender, MouseEventArgs e)
        {
            Moving(e.GetPosition(pn));
        }

        private void LbPotato_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Debug.WriteLine("finish");
            MoveFinish();
        }
        
        private void PotatoItem_OnMoveStart(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("start");
            PotatoItem item = sender as PotatoItem;
            if (item == null) return;
            MoveStart(item.DataContext as Potato);
        }
        #endregion*/
    }
}
